package com.zzx.schoolfellow.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vdurmont.emoji.EmojiParser;
import com.zzx.schoolfellow.common.api.ApiResult;
import com.zzx.schoolfellow.jwt.JwtUtil;
import com.zzx.schoolfellow.model.dto.LoginDTO;
import com.zzx.schoolfellow.model.dto.RegisterDTO;
import com.zzx.schoolfellow.model.dto.ResetPasswordDTO;
import com.zzx.schoolfellow.model.entity.BmsPost;
import com.zzx.schoolfellow.model.entity.UmsUser;
import com.zzx.schoolfellow.service.IBmsPostService;
import com.zzx.schoolfellow.service.IUmsUserService;
import com.zzx.schoolfellow.utils.MD5Utils;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;


/**
 * @program: schoolfeoolw_backend
 * @description: 用户控制层
 * @author: zzx
 * @create: 2023-03-14 21:59
 **/
@RestController
@RequestMapping("/ums/user")
public class UmsUserController extends BaseController {
    @Resource
    private IUmsUserService iUmsUserService;
    @Resource
    private IBmsPostService iBmsPostService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ApiResult<Map<String, Object>> register(@Valid @RequestBody RegisterDTO dto) {
        UmsUser user = iUmsUserService.executeRegister(dto);
        if (ObjectUtils.isEmpty(user)) {
            return ApiResult.failed("账号注册失败");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("user", user);
        return ApiResult.success(map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResult<Map<String, String>> login(@Valid @RequestBody LoginDTO dto) {
        String token = iUmsUserService.executeLogin(dto);
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        Map<String, String> map = new HashMap<>(16);
        map.put("token", token);
        return ApiResult.success(map, "登录成功");
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ApiResult<UmsUser> getUser(@RequestHeader(value = JwtUtil.USER_NAME) String userName) {
        UmsUser user = iUmsUserService.getUserByUsername(userName);
        return ApiResult.success(user);
    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ApiResult<Object> logOut() {
        return ApiResult.success(null, "注销成功");
    }

    @GetMapping("/{username}")
    public ApiResult<Map<String, Object>> getUserByName(@PathVariable("username") String username,
                                                        @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map<String, Object> map = new HashMap<>(16);
        UmsUser user = iUmsUserService.getUserByUsername(username);
        Assert.notNull(user, "用户不存在");
        Page<BmsPost> page = iBmsPostService.page(new Page<>(pageNo, size),
                new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getUserId, user.getId()));
        map.put("user", user);
        map.put("topics", page);
        return ApiResult.success(map);
    }
    // 获取用户列表
    @GetMapping("/lists")
    public List<UmsUser> getUserList() {
        return iUmsUserService.getUserList();
    }

    //    @GetMapping("/list")
//    public List<UmsUser> getUserList() {
//        return iUmsUserService.list();
//    }
    @GetMapping("/list")
    public List<UmsUser> getUserList(@RequestParam("keyword") String keyword) {
        List<UmsUser> list;
        if (Objects.equals(keyword, "")) {
            list = iUmsUserService.list();
        } else {
            list = iUmsUserService.list(new QueryWrapper<UmsUser>()
                    .like("username", keyword));
        }
        return list;
    }

    @DeleteMapping("/delete/{id}")
    public ApiResult<String> deleteUser(@PathVariable("id") String id) {
        UmsUser byId = iUmsUserService.getById(id);
        Assert.notNull(byId, "来晚一步，用户已不存在");
        iUmsUserService.removeById(id);
        return ApiResult.success(null, "删除成功");
    }

    @PostMapping("/updated")
    public ApiResult<UmsUser> updateUser(@Valid @RequestBody UmsUser umsUser) {
        iUmsUserService.updateById(umsUser);
        return ApiResult.success(umsUser);
    }

    @PostMapping("/resetPassword")
    public void resetPassword(@RequestBody ResetPasswordDTO form) {
        UmsUser user = iUmsUserService.getUserByUsername(form.getUsername());
        if (user != null) {
            user.setPassword(MD5Utils.getPwd(form.getPassword())); // 使用加密算法加密新密码
            iUmsUserService.updateById(user);
        } else {
            throw new RuntimeException("用户名或邮箱错误！");
        }
    }

    @GetMapping("/user/{id}")
    public UmsUser getUserById(@PathVariable Long id) throws NotFoundException {
        UmsUser user = iUmsUserService.getById(id);
        if (user == null) {
            throw new NotFoundException("User not found");
        }

        return user;
    }
}
